<template>
  <div v-loading="loadFlag" class="personalInfoPage">
    <div class="personalBox">
      <div class="boxImg">
        <!-- <img :src="imgUrl" alt="" width="100%"> -->
        <el-upload
          class="avatar-uploader"
          action="/bar/uploadUserImg"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img :src="imageUrl" class="avatar" width="80px"
               height="80px"
          >
          <!-- <i v-else class="el-icon-plus avatar-uploader-icon" /> -->
        </el-upload>
      </div>
      点击头像进行切换~
      <br>

      <el-popover
        v-model="visible"
        placement="bottom"
        width="160"
      >
        <p>是否确定退出登录？</p>
        <div style="text-align: right; margin: 0">
          <el-button size="mini" type="text" @click="visible = false">
            取消
          </el-button>
          <el-button type="primary" size="mini" @click="signOut">
            确定
          </el-button>
        </div>
        <el-button
          slot="reference"
          type="danger"
          round
          size="small"
        >
          注销
        </el-button>
      </el-popover>
    </div>
    <div class="myDynamic infinite-list">
      <div class="dynamicTop">
        <div class="erect" />
        资料修改
      </div>
      <div class="dynamicItem">
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          status-icon
          :rules="rules"
          label-width="45px"
          class="demo-ruleForm"
          label-position="left"
          :disabled="disFlag"
        >
          <el-form-item label="账号:" prop="username">
            <el-input v-model="ruleForm.username" autocomplete="off" />
          </el-form-item>
          <el-form-item label="密码:" prop="password">
            <el-input
              v-model="ruleForm.password"
              type="password"
              autocomplete="off"
              show-password
            />
          </el-form-item>
          <el-form-item label="手机:" prop="phone">
            <el-input v-model="ruleForm.phone" />
          </el-form-item>
          <!-- <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">
              提交
            </el-button>
            <el-button @click="resetForm('ruleForm')">
              重置
            </el-button>
          </el-form-item> -->
        </el-form>
        <div class="buttonCls">
          <el-button
            v-show="btnFlag"
            type="primary"
            icon="el-icon-edit"
            size="small"
            round
            @click="btnFlag=false;disFlag=false"
          >
            编辑
          </el-button>
          <div v-show="!btnFlag">
            <el-button
              type="success"
              icon="el-icon-upload"
              size="small"
              round
              @click="onSubmitEdit"
            >
              提交
            </el-button>
            <el-button
              type="danger"
              icon="el-icon-refresh-left"
              size="small"
              round
              @click="cancel"
            >
              取消
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import eventBus from '@/api/eventBus';
import { updateUserImg, updateUserInfo } from '../../api/user';
export default {
  data() {
    var checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('年龄不能为空'));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error('请输入数字值'));
        } else {
          if (value < 18) {
            callback(new Error('必须年满18岁'));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      imageUrl: require('../../assets/images/userPicture.jpeg'),
      visible: false,
      disFlag: true,
      btnFlag: true,
      loadFlag: false,
      ruleForm: {
        username: '',
        password: '',
        phone: ''
      },
      originData: {
        username: '',
        password: '',
        phone: ''
      },
      rules: {
        pass: [
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPass: [
          { validator: validatePass2, trigger: 'blur' }
        ],
        age: [
          { validator: checkAge, trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    eventBus.$emit('changeTitle', '个人主页');
    this.imageUrl = process.env.VUE_APP_DEV_TARGET + this.$store.getters.userInfo.userImg;
  },
  mounted() {
    const userInfo = this.$store.getters.userInfo;
    this.ruleForm = {
      username: userInfo.userName,
      password: userInfo.password,
      phone: userInfo.userPhone
    };
    this.originData = userInfo;
  },
  beforeDestroy() {
    eventBus.$emit('changeTitle', '个人中心');
  },
  methods: {
    handleAvatarSuccess(res) {
      const params = {
        id: this.$store.getters.userInfo.uid,
        userImg: res.url
      };
      updateUserImg(params).then((res) => {
        if (res.data.code === 200) {
          this.$message({
            showClose: true,
            message: '更换成功',
            type: 'success'
          });
        }
        this.imageUrl = process.env.VUE_APP_DEV_TARGET + params.userImg;
        const userInfo = this.$store.getters.userInfo;
        userInfo.userImg = params.userImg;
        this.$store.dispatch('setUserInfo', userInfo);
      });
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    signOut() {
      this.$router.push({ name: 'login' });
    },
    cancel() {
      this.ruleForm = {
        username: this.originData.userName,
        password: this.originData.password,
        phone: this.originData.userPhone
      };
      this.btnFlag = true;
      this.disFlag = true;
    },
    async onSubmitEdit() {
      const userInfo = this.$store.getters.userInfo;
      userInfo.userName = this.ruleForm.username;
      userInfo.password = this.ruleForm.password;
      userInfo.userPhone = this.ruleForm.phone;
      this.loadFlag = true;
      const params = {
        username: this.ruleForm.username,
        password: this.ruleForm.password,
        userphone: this.ruleForm.phone,
        uid: userInfo.uid
      };
      await updateUserInfo(params).then(res => {
        if (res.data.code === 200) {
          this.$store.dispatch('setUserInfo', userInfo);
          setTimeout(() => {
            this.btnFlag = true;
            this.disFlag = true;
            this.loadFlag = false;
          }, 500);
        }
      });
      this.$message({
        showClose: true,
        message: '修改成功',
        type: 'success'
      });
    }
  }
};
</script>
<style lang="scss">
.el-progress-bar__outer{
  background: #F56C6C;
}
.personalInfoPage{
  .el-button{
    margin-top: 20px;
    padding: 9px 20px;
  }
  .el-input.is-disabled .el-input__inner{
    background-color: #fff;
  }
}

</style>
<style lang="scss" scoped>
.personalInfoPage{
  width: 100%;
  height: 100%;
  overflow-y: auto;
  .personalBox{
    width: 90%;
    height: 200px;
    background: #fff;
    text-align: center;
    font-size: 12px;
    color: #C0C4CC;
    border-radius: 10px;
    margin: 10px auto;
    box-shadow: 2px 2px 5px rgb(226, 226, 226);
    overflow: hidden;
    // line-height: 32px;
    .boxImg{
      margin: 10px auto;
      width: 80px;
      height: 80px;
      border-radius: 100%;
      overflow: hidden;
    }
  }
  .myDynamic{
    width: 90%;
    // max-height: calc(100% - 180px);
    margin: 0 auto;
    position: relative;
    .dynamicTop{
      width: 100%;
      height: 30px;
      display: flex;
      font-size: 14px;
      color: #5e5e5e;
      font-weight: bold;
      align-items: center;
      .erect{
        width: 4px;
        height: 20px;
        margin-right: 8px;
        background: #409EFF;
      }
    }
    .dynamicItem{
      width: 100%;
      margin-top: 20px;
      background: #fff;
      border-radius: 10px;
      box-shadow: 2px 2px 5px rgb(226, 226, 226);
      padding: 20px 10px;
      box-sizing: border-box;
      // border: 1px solid gray;
      .buttonCls{
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }
  }
}
</style>
